import 'package:injectable/injectable.dart';
import 'package:shared_preferences/shared_preferences.dart';

/// SharedPreferences 存储服务
/// 提供本地数据持久化功能
@lazySingleton
class StorageService {
  SharedPreferences? _prefs;

  /// 初始化 SharedPreferences 实例
  Future<void> initialize() async {
    _prefs ??= await SharedPreferences.getInstance();
  }

  /// 确保 SharedPreferences 已初始化
  Future<void> _ensureInitialized() async {
    if (_prefs == null) {
      await initialize();
    }
  }

  /// 保存字符串值
  Future<bool> persistString(String key, String value) async {
    await _ensureInitialized();
    return await _prefs!.setString(key, value);
  }

  /// 获取字符串值
  Future<String?> retrieveString(String key) async {
    await _ensureInitialized();
    return _prefs!.getString(key);
  }

  /// 保存整数值
  Future<bool> persistInt(String key, int value) async {
    await _ensureInitialized();
    return await _prefs!.setInt(key, value);
  }

  /// 获取整数值
  Future<int?> retrieveInt(String key) async {
    await _ensureInitialized();
    return _prefs!.getInt(key);
  }

  /// 保存布尔值
  Future<bool> persistBool(String key, bool value) async {
    await _ensureInitialized();
    return await _prefs!.setBool(key, value);
  }

  /// 获取布尔值
  Future<bool?> retrieveBool(String key) async {
    await _ensureInitialized();
    return _prefs!.getBool(key);
  }

  /// 保存双精度浮点数值
  Future<bool> persistDouble(String key, double value) async {
    await _ensureInitialized();
    return await _prefs!.setDouble(key, value);
  }

  /// 获取双精度浮点数值
  Future<double?> retrieveDouble(String key) async {
    await _ensureInitialized();
    return _prefs!.getDouble(key);
  }

  /// 保存字符串列表
  Future<bool> persistStringList(String key, List<String> value) async {
    await _ensureInitialized();
    return await _prefs!.setStringList(key, value);
  }

  /// 获取字符串列表
  Future<List<String>?> retrieveStringList(String key) async {
    await _ensureInitialized();
    return _prefs!.getStringList(key);
  }

  /// 删除指定键的值
  Future<bool> removeKey(String key) async {
    await _ensureInitialized();
    return await _prefs!.remove(key);
  }

  /// 检查是否存在指定键
  Future<bool> containsKey(String key) async {
    await _ensureInitialized();
    return _prefs!.containsKey(key);
  }

  /// 获取所有键
  Future<Set<String>> getAllKeys() async {
    await _ensureInitialized();
    return _prefs!.getKeys();
  }

  /// 清空所有数据
  Future<bool> clearAll() async {
    await _ensureInitialized();
    return await _prefs!.clear();
  }

  /// 重新加载数据
  Future<void> reload() async {
    await _ensureInitialized();
    await _prefs!.reload();
  }
}
